{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "#  序列到序列学习（seq2seq）\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "sys.path.append('..')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "origin_pos": 2,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import collections\n",
    "import math\n",
    "import mindspore\n",
    "import mindspore.nn as nn\n",
    "import mindspore.ops as ops\n",
    "from d2l import mindspore as d2l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "实现循环神经网络编码器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "origin_pos": 6,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class Seq2SeqEncoder(d2l.Encoder):\n",
    "    \"\"\"用于序列到序列学习的循环神经网络编码器\"\"\"\n",
    "    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n",
    "                 dropout=0., **kwargs):\n",
    "        super(Seq2SeqEncoder, self).__init__(**kwargs)\n",
    "        # 嵌入层\n",
    "        self.embedding = nn.Embedding(vocab_size, embed_size)\n",
    "        self.rnn = nn.GRU(embed_size, num_hiddens, num_layers,\n",
    "                          dropout=dropout)\n",
    "        \n",
    "    def construct(self, X, X_len=None):\n",
    "        # 输出'X'的形状：(batch_size,num_steps,embed_size)\n",
    "        X = self.embedding(X)\n",
    "        # 在循环神经网络模型中，第一个轴对应于时间步\n",
    "        X = X.permute(1, 0, 2)\n",
    "        output, state = self.rnn(X)\n",
    "        return output, state"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "上述编码器的实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "origin_pos": 10,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(7, 4, 16)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "encoder = Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16,\n",
    "                         num_layers=2)\n",
    "encoder.set_train(False)\n",
    "X = d2l.zeros((4, 7), dtype=mindspore.int32)\n",
    "output, state = encoder(X)\n",
    "output.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "origin_pos": 14,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(2, 4, 16)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "state.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "解码器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "origin_pos": 18,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class Seq2SeqDecoder(d2l.Decoder):\n",
    "    \"\"\"用于序列到序列学习的循环神经网络解码器\"\"\"\n",
    "    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n",
    "                 dropout=0., **kwargs):\n",
    "        super(Seq2SeqDecoder, self).__init__(**kwargs)\n",
    "        self.embedding = nn.Embedding(vocab_size, embed_size)\n",
    "        self.rnn = nn.GRU(embed_size + num_hiddens, num_hiddens, num_layers,\n",
    "                          dropout=dropout)\n",
    "        self.dense = nn.Dense(num_hiddens, vocab_size) # weight_init='xavier_uniform'\n",
    "\n",
    "    def init_state(self, enc_outputs, *args):\n",
    "        return enc_outputs[1]\n",
    "\n",
    "    def construct(self, X, state):\n",
    "        # 输出'X'的形状：(batch_size,num_steps,embed_size)\n",
    "        X = self.embedding(X).permute(1, 0, 2)\n",
    "        # 广播context，使其具有与X相同的num_steps\n",
    "        context = ops.repeat_elements(state[-1:], rep=X.shape[0], axis=0)\n",
    "        X_and_context = d2l.concat((X, context), 2)\n",
    "        output, state = self.rnn(X_and_context, state)\n",
    "        output = self.dense(output).permute(1, 0, 2)\n",
    "        # output的形状:(batch_size,num_steps,vocab_size)\n",
    "        # state的形状:(num_layers,batch_size,num_hiddens)\n",
    "        return output, state"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "实例化解码器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "origin_pos": 22,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((4, 7, 10), (2, 4, 16))"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "decoder = Seq2SeqDecoder(vocab_size=10, embed_size=8, num_hiddens=16,\n",
    "                         num_layers=2)\n",
    "decoder.set_train(False)\n",
    "state = decoder.init_state(encoder(X))\n",
    "output, state = decoder(X, state)\n",
    "output.shape, state.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "通过零值化屏蔽不相关的项"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "origin_pos": 26,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tensor(shape=[2, 3], dtype=Int64, value=\n",
       "[[1, 0, 0],\n",
       " [4, 5, 0]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def sequence_mask(X, valid_len, value=0):\n",
    "    \"\"\"在序列中屏蔽不相关的项\"\"\"\n",
    "    maxlen = X.shape[1]\n",
    "    mask = ops.arange((maxlen), dtype=mindspore.float32)[None, :] < valid_len[:, None]\n",
    "    X[~mask] = value\n",
    "    return X\n",
    "\n",
    "X = mindspore.Tensor([[1, 2, 3], [4, 5, 6]])\n",
    "sequence_mask(X, mindspore.Tensor([1, 2]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "我们还可以使用此函数屏蔽最后几个轴上的所有项"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "origin_pos": 30,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:19:51.661.294 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 43\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Tensor(shape=[2, 3, 4], dtype=Float32, value=\n",
       "[[[ 1.00000000e+00,  1.00000000e+00,  1.00000000e+00,  1.00000000e+00],\n",
       "  [-1.00000000e+00, -1.00000000e+00, -1.00000000e+00, -1.00000000e+00],\n",
       "  [-1.00000000e+00, -1.00000000e+00, -1.00000000e+00, -1.00000000e+00]],\n",
       " [[ 1.00000000e+00,  1.00000000e+00,  1.00000000e+00,  1.00000000e+00],\n",
       "  [ 1.00000000e+00,  1.00000000e+00,  1.00000000e+00,  1.00000000e+00],\n",
       "  [-1.00000000e+00, -1.00000000e+00, -1.00000000e+00, -1.00000000e+00]]])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = d2l.ones((2, 3, 4))\n",
    "sequence_mask(X, mindspore.Tensor([1, 2]), value=-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "通过扩展softmax交叉熵损失函数来遮蔽不相关的预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "origin_pos": 34,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class MaskedSoftmaxCELoss(nn.Cell):\n",
    "    \"\"\"带遮蔽的softmax交叉熵损失函数\"\"\"\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        self.softmax_ce_loss = nn.CrossEntropyLoss()\n",
    "    \n",
    "    # pred的形状：(batch_size,num_steps,vocab_size)\n",
    "    # label的形状：(batch_size,num_steps)\n",
    "    # valid_len的形状：(batch_size,)\n",
    "    def construct(self, pred, label, valid_len):\n",
    "        weights = ops.ones_like(label)\n",
    "        weights = sequence_mask(weights, valid_len)\n",
    "        unweighted_loss = self.softmax_ce_loss(pred.permute(0, 2, 1), label)\n",
    "        weighted_loss = (unweighted_loss * weights).mean(axis=1)\n",
    "        return weighted_loss"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "代码健全性检查"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "origin_pos": 38,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:19:51.698.753 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Tensor(shape=[3], dtype=Float32, value= [ 2.30258799e+00,  1.15129399e+00,  0.00000000e+00])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "loss = MaskedSoftmaxCELoss()\n",
    "loss(ops.ones((3, 4, 10)), ops.ones((3, 4), dtype=mindspore.int32),\n",
    "     mindspore.Tensor([4, 2, 0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "训练"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "origin_pos": 42,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab):\n",
    "    \"\"\"训练序列到序列模型\"\"\"\n",
    "\n",
    "    optimizer = nn.Adam(net.trainable_params(), lr)\n",
    "    loss = MaskedSoftmaxCELoss()\n",
    "    animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n",
    "                     xlim=[10, num_epochs])\n",
    "    def forward_fn(X, dec_input, X_valid_len, Y, Y_valid_len):\n",
    "        pred, _ = net(X, dec_input, X_valid_len)\n",
    "        l = loss(pred, Y, Y_valid_len)\n",
    "        return l\n",
    "    grad_fn = mindspore.value_and_grad(forward_fn, None, net.trainable_params(), has_aux=False)\n",
    "    \n",
    "    for epoch in range(num_epochs):\n",
    "        timer = d2l.Timer()\n",
    "        metric = d2l.Accumulator(2)  # 训练损失总和，词元数量\n",
    "        net.set_train()\n",
    "        for batch in data_iter:\n",
    "            X, X_valid_len, Y, Y_valid_len = [x.astype(d2l.int32) for x in batch]\n",
    "            # print(X.shape, X_valid_len, Y.shape, Y_valid_len)\n",
    "            bos = mindspore.Tensor([tgt_vocab['<bos>']] * Y.shape[0], dtype=mindspore.int32).reshape(-1, 1)\n",
    "            dec_input = ops.concat([bos, Y[:, :-1]], 1)  # 强制教学\n",
    "            l, grads = grad_fn(X, dec_input, X_valid_len, Y, Y_valid_len)\n",
    "            optimizer(grads)\n",
    "            num_tokens = Y_valid_len.sum()\n",
    "            metric.add(l.sum(), num_tokens)\n",
    "        if (epoch + 1) % 10 == 0:\n",
    "            animator.add(epoch + 1, (metric[0] / metric[1],))\n",
    "    print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '\n",
    "        f'tokens/sec')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "创建和训练一个循环神经网络“编码器－解码器”模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "origin_pos": 45,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "正在从http://d2l-data.s3-accelerate.amazonaws.com/fra-eng.zip下载../data/fra-eng.zip...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:08.295.649 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:09.069.676 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:09.257.903 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:09.440.888 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:09.647.505 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:09.828.180 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:10.030.248 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:10.218.455 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:10.422.382 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:10.736.633 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:11.444.787 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:12.099.160 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:12.770.564 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:13.479.923 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:14.137.617 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:14.787.212 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:15.406.803 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:16.107.824 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:16.800.813 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:17.448.030 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:18.108.732 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:18.759.467 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:19.549.408 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:20.214.724 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:20.910.877 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:21.528.300 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:22.209.505 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:22.866.264 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:23.497.657 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:24.126.400 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:24.803.424 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:25.461.996 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:26.128.464 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:26.788.311 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:27.459.281 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:28.111.665 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:28.774.769 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:29.435.291 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:30.072.972 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:30.720.423 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:31.363.935 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:32.011.091 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:32.672.154 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:33.332.977 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:34.036.773 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:34.704.538 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[WARNING] CORE(25029,7f0882714080,python):2023-02-19-10:25:35.350.052 [mindspore/core/ops/fill.cc:202] FillInferValue] value type is not same as given dtype, value type id is 35 and given dtype id is 34\n",
      "[ERROR] KERNEL(25029,7f0882714080,python):2023-02-19-10:25:35.729.324 [mindspore/ccsrc/plugin/device/cpu/kernel/unsorted_segment_arithmetic_cpu_kernel.cc:112] LaunchKernel] For 'UnsortedSegmentSum', segment_ids value should be [0, 184)\n"
     ]
    },
    {
     "ename": "RuntimeError",
     "evalue": "Launch kernel failed, name:Default/UnsortedSegmentSum-op2003\n\n----------------------------------------------------\n- C++ Call Stack: (For framework developers)\n----------------------------------------------------\nmindspore/ccsrc/runtime/pynative/run_op_helper.cc:569 LaunchKernelsDynamic\n",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mRuntimeError\u001b[0m                              Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[13], line 12\u001b[0m\n\u001b[1;32m      8\u001b[0m decoder \u001b[38;5;241m=\u001b[39m Seq2SeqDecoder(\u001b[38;5;28mlen\u001b[39m(tgt_vocab), embed_size, num_hiddens, num_layers,\n\u001b[1;32m      9\u001b[0m                         dropout)\n\u001b[1;32m     10\u001b[0m net \u001b[38;5;241m=\u001b[39m d2l\u001b[38;5;241m.\u001b[39mEncoderDecoder(encoder, decoder)\n\u001b[0;32m---> 12\u001b[0m \u001b[43mtrain_seq2seq\u001b[49m\u001b[43m(\u001b[49m\u001b[43mnet\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtrain_iter\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mlr\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mnum_epochs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtgt_vocab\u001b[49m\u001b[43m)\u001b[49m\n",
      "Cell \u001b[0;32mIn[12], line 23\u001b[0m, in \u001b[0;36mtrain_seq2seq\u001b[0;34m(net, data_iter, lr, num_epochs, tgt_vocab)\u001b[0m\n\u001b[1;32m     21\u001b[0m bos \u001b[38;5;241m=\u001b[39m mindspore\u001b[38;5;241m.\u001b[39mTensor([tgt_vocab[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m<bos>\u001b[39m\u001b[38;5;124m'\u001b[39m]] \u001b[38;5;241m*\u001b[39m Y\u001b[38;5;241m.\u001b[39mshape[\u001b[38;5;241m0\u001b[39m], dtype\u001b[38;5;241m=\u001b[39mmindspore\u001b[38;5;241m.\u001b[39mint32)\u001b[38;5;241m.\u001b[39mreshape(\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m1\u001b[39m)\n\u001b[1;32m     22\u001b[0m dec_input \u001b[38;5;241m=\u001b[39m ops\u001b[38;5;241m.\u001b[39mconcat([bos, Y[:, :\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m]], \u001b[38;5;241m1\u001b[39m)  \u001b[38;5;66;03m# 强制教学\u001b[39;00m\n\u001b[0;32m---> 23\u001b[0m l, grads \u001b[38;5;241m=\u001b[39m \u001b[43mgrad_fn\u001b[49m\u001b[43m(\u001b[49m\u001b[43mX\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mdec_input\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mX_valid_len\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mY\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mY_valid_len\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m     24\u001b[0m optimizer(grads)\n\u001b[1;32m     25\u001b[0m num_tokens \u001b[38;5;241m=\u001b[39m Y_valid_len\u001b[38;5;241m.\u001b[39msum()\n",
      "File \u001b[0;32m/data/miniconda3/envs/ms_d2l/lib/python3.8/site-packages/mindspore/ops/composite/base.py:605\u001b[0m, in \u001b[0;36m_Grad.__call__.<locals>.after_grad\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m    604\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mafter_grad\u001b[39m(\u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs):\n\u001b[0;32m--> 605\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mgrad_\u001b[49m\u001b[43m(\u001b[49m\u001b[43mfn_\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mweights\u001b[49m\u001b[43m)\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
      "File \u001b[0;32m/data/miniconda3/envs/ms_d2l/lib/python3.8/site-packages/mindspore/common/api.py:101\u001b[0m, in \u001b[0;36m_wrap_func.<locals>.wrapper\u001b[0;34m(*arg, **kwargs)\u001b[0m\n\u001b[1;32m     99\u001b[0m \u001b[38;5;129m@wraps\u001b[39m(fn)\n\u001b[1;32m    100\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mwrapper\u001b[39m(\u001b[38;5;241m*\u001b[39marg, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs):\n\u001b[0;32m--> 101\u001b[0m     results \u001b[38;5;241m=\u001b[39m \u001b[43mfn\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43marg\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    102\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m _convert_python_data(results)\n",
      "File \u001b[0;32m/data/miniconda3/envs/ms_d2l/lib/python3.8/site-packages/mindspore/ops/composite/base.py:584\u001b[0m, in \u001b[0;36m_Grad.__call__.<locals>.after_grad\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m    582\u001b[0m res \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_pynative_forward_run(fn, grad_, args, kwargs)\n\u001b[1;32m    583\u001b[0m _pynative_executor\u001b[38;5;241m.\u001b[39mgrad(fn, grad_, weights, grad_position, \u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n\u001b[0;32m--> 584\u001b[0m out \u001b[38;5;241m=\u001b[39m \u001b[43m_pynative_executor\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    585\u001b[0m out \u001b[38;5;241m=\u001b[39m _grads_divided_by_device_num_if_recomputation(out)\n\u001b[1;32m    586\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mreturn_ids \u001b[38;5;129;01mand\u001b[39;00m out:\n",
      "File \u001b[0;32m/data/miniconda3/envs/ms_d2l/lib/python3.8/site-packages/mindspore/common/api.py:986\u001b[0m, in \u001b[0;36m_PyNativeExecutor.__call__\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m    979\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m__call__\u001b[39m(\u001b[38;5;28mself\u001b[39m):\n\u001b[1;32m    980\u001b[0m     \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[1;32m    981\u001b[0m \u001b[38;5;124;03m    PyNative executor run grad graph.\u001b[39;00m\n\u001b[1;32m    982\u001b[0m \n\u001b[1;32m    983\u001b[0m \u001b[38;5;124;03m    Return:\u001b[39;00m\n\u001b[1;32m    984\u001b[0m \u001b[38;5;124;03m        The return object after running grad graph.\u001b[39;00m\n\u001b[1;32m    985\u001b[0m \u001b[38;5;124;03m    \"\"\"\u001b[39;00m\n\u001b[0;32m--> 986\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_executor\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n",
      "\u001b[0;31mRuntimeError\u001b[0m: Launch kernel failed, name:Default/UnsortedSegmentSum-op2003\n\n----------------------------------------------------\n- C++ Call Stack: (For framework developers)\n----------------------------------------------------\nmindspore/ccsrc/runtime/pynative/run_op_helper.cc:569 LaunchKernelsDynamic\n"
     ]
    },
    {
     "data": {
      "image/svg+xml": [
       "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n",
       "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n",
       "  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n",
       "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"240.554688pt\" height=\"173.477344pt\" viewBox=\"0 0 240.554688 173.477344\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n",
       " <metadata>\n",
       "  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n",
       "   <cc:Work>\n",
       "    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n",
       "    <dc:date>2023-02-19T10:25:36.794701</dc:date>\n",
       "    <dc:format>image/svg+xml</dc:format>\n",
       "    <dc:creator>\n",
       "     <cc:Agent>\n",
       "      <dc:title>Matplotlib v3.6.2, https://matplotlib.org/</dc:title>\n",
       "     </cc:Agent>\n",
       "    </dc:creator>\n",
       "   </cc:Work>\n",
       "  </rdf:RDF>\n",
       " </metadata>\n",
       " <defs>\n",
       "  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n",
       " </defs>\n",
       " <g id=\"figure_1\">\n",
       "  <g id=\"patch_1\">\n",
       "   <path d=\"M 0 173.477344 \n",
       "L 240.554688 173.477344 \n",
       "L 240.554688 0 \n",
       "L 0 0 \n",
       "z\n",
       "\" style=\"fill: #ffffff\"/>\n",
       "  </g>\n",
       "  <g id=\"axes_1\">\n",
       "   <g id=\"patch_2\">\n",
       "    <path d=\"M 30.103125 149.599219 \n",
       "L 225.403125 149.599219 \n",
       "L 225.403125 10.999219 \n",
       "L 30.103125 10.999219 \n",
       "z\n",
       "\" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_1\">\n",
       "    <g id=\"xtick_1\">\n",
       "     <g id=\"line2d_1\">\n",
       "      <defs>\n",
       "       <path id=\"meb54f4bdcf\" d=\"M 0 0 \n",
       "L 0 3.5 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#meb54f4bdcf\" x=\"30.103125\" y=\"149.599219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_1\">\n",
       "      <!-- 0.0 -->\n",
       "      <g transform=\"translate(22.151563 164.197656) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \n",
       "Q 1547 4250 1301 3770 \n",
       "Q 1056 3291 1056 2328 \n",
       "Q 1056 1369 1301 889 \n",
       "Q 1547 409 2034 409 \n",
       "Q 2525 409 2770 889 \n",
       "Q 3016 1369 3016 2328 \n",
       "Q 3016 3291 2770 3770 \n",
       "Q 2525 4250 2034 4250 \n",
       "z\n",
       "M 2034 4750 \n",
       "Q 2819 4750 3233 4129 \n",
       "Q 3647 3509 3647 2328 \n",
       "Q 3647 1150 3233 529 \n",
       "Q 2819 -91 2034 -91 \n",
       "Q 1250 -91 836 529 \n",
       "Q 422 1150 422 2328 \n",
       "Q 422 3509 836 4129 \n",
       "Q 1250 4750 2034 4750 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \n",
       "L 1344 794 \n",
       "L 1344 0 \n",
       "L 684 0 \n",
       "L 684 794 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_2\">\n",
       "     <g id=\"line2d_2\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meb54f4bdcf\" x=\"69.163125\" y=\"149.599219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_2\">\n",
       "      <!-- 0.2 -->\n",
       "      <g transform=\"translate(61.211563 164.197656) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \n",
       "L 3431 531 \n",
       "L 3431 0 \n",
       "L 469 0 \n",
       "L 469 531 \n",
       "Q 828 903 1448 1529 \n",
       "Q 2069 2156 2228 2338 \n",
       "Q 2531 2678 2651 2914 \n",
       "Q 2772 3150 2772 3378 \n",
       "Q 2772 3750 2511 3984 \n",
       "Q 2250 4219 1831 4219 \n",
       "Q 1534 4219 1204 4116 \n",
       "Q 875 4013 500 3803 \n",
       "L 500 4441 \n",
       "Q 881 4594 1212 4672 \n",
       "Q 1544 4750 1819 4750 \n",
       "Q 2544 4750 2975 4387 \n",
       "Q 3406 4025 3406 3419 \n",
       "Q 3406 3131 3298 2873 \n",
       "Q 3191 2616 2906 2266 \n",
       "Q 2828 2175 2409 1742 \n",
       "Q 1991 1309 1228 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-32\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_3\">\n",
       "     <g id=\"line2d_3\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meb54f4bdcf\" x=\"108.223125\" y=\"149.599219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_3\">\n",
       "      <!-- 0.4 -->\n",
       "      <g transform=\"translate(100.271563 164.197656) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-34\" d=\"M 2419 4116 \n",
       "L 825 1625 \n",
       "L 2419 1625 \n",
       "L 2419 4116 \n",
       "z\n",
       "M 2253 4666 \n",
       "L 3047 4666 \n",
       "L 3047 1625 \n",
       "L 3713 1625 \n",
       "L 3713 1100 \n",
       "L 3047 1100 \n",
       "L 3047 0 \n",
       "L 2419 0 \n",
       "L 2419 1100 \n",
       "L 313 1100 \n",
       "L 313 1709 \n",
       "L 2253 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-34\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_4\">\n",
       "     <g id=\"line2d_4\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meb54f4bdcf\" x=\"147.283125\" y=\"149.599219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_4\">\n",
       "      <!-- 0.6 -->\n",
       "      <g transform=\"translate(139.331563 164.197656) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-36\" d=\"M 2113 2584 \n",
       "Q 1688 2584 1439 2293 \n",
       "Q 1191 2003 1191 1497 \n",
       "Q 1191 994 1439 701 \n",
       "Q 1688 409 2113 409 \n",
       "Q 2538 409 2786 701 \n",
       "Q 3034 994 3034 1497 \n",
       "Q 3034 2003 2786 2293 \n",
       "Q 2538 2584 2113 2584 \n",
       "z\n",
       "M 3366 4563 \n",
       "L 3366 3988 \n",
       "Q 3128 4100 2886 4159 \n",
       "Q 2644 4219 2406 4219 \n",
       "Q 1781 4219 1451 3797 \n",
       "Q 1122 3375 1075 2522 \n",
       "Q 1259 2794 1537 2939 \n",
       "Q 1816 3084 2150 3084 \n",
       "Q 2853 3084 3261 2657 \n",
       "Q 3669 2231 3669 1497 \n",
       "Q 3669 778 3244 343 \n",
       "Q 2819 -91 2113 -91 \n",
       "Q 1303 -91 875 529 \n",
       "Q 447 1150 447 2328 \n",
       "Q 447 3434 972 4092 \n",
       "Q 1497 4750 2381 4750 \n",
       "Q 2619 4750 2861 4703 \n",
       "Q 3103 4656 3366 4563 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-36\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_5\">\n",
       "     <g id=\"line2d_5\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meb54f4bdcf\" x=\"186.343125\" y=\"149.599219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_5\">\n",
       "      <!-- 0.8 -->\n",
       "      <g transform=\"translate(178.391563 164.197656) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-38\" d=\"M 2034 2216 \n",
       "Q 1584 2216 1326 1975 \n",
       "Q 1069 1734 1069 1313 \n",
       "Q 1069 891 1326 650 \n",
       "Q 1584 409 2034 409 \n",
       "Q 2484 409 2743 651 \n",
       "Q 3003 894 3003 1313 \n",
       "Q 3003 1734 2745 1975 \n",
       "Q 2488 2216 2034 2216 \n",
       "z\n",
       "M 1403 2484 \n",
       "Q 997 2584 770 2862 \n",
       "Q 544 3141 544 3541 \n",
       "Q 544 4100 942 4425 \n",
       "Q 1341 4750 2034 4750 \n",
       "Q 2731 4750 3128 4425 \n",
       "Q 3525 4100 3525 3541 \n",
       "Q 3525 3141 3298 2862 \n",
       "Q 3072 2584 2669 2484 \n",
       "Q 3125 2378 3379 2068 \n",
       "Q 3634 1759 3634 1313 \n",
       "Q 3634 634 3220 271 \n",
       "Q 2806 -91 2034 -91 \n",
       "Q 1263 -91 848 271 \n",
       "Q 434 634 434 1313 \n",
       "Q 434 1759 690 2068 \n",
       "Q 947 2378 1403 2484 \n",
       "z\n",
       "M 1172 3481 \n",
       "Q 1172 3119 1398 2916 \n",
       "Q 1625 2713 2034 2713 \n",
       "Q 2441 2713 2670 2916 \n",
       "Q 2900 3119 2900 3481 \n",
       "Q 2900 3844 2670 4047 \n",
       "Q 2441 4250 2034 4250 \n",
       "Q 1625 4250 1398 4047 \n",
       "Q 1172 3844 1172 3481 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-38\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_6\">\n",
       "     <g id=\"line2d_6\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#meb54f4bdcf\" x=\"225.403125\" y=\"149.599219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_6\">\n",
       "      <!-- 1.0 -->\n",
       "      <g transform=\"translate(217.451563 164.197656) scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-31\" d=\"M 794 531 \n",
       "L 1825 531 \n",
       "L 1825 4091 \n",
       "L 703 3866 \n",
       "L 703 4441 \n",
       "L 1819 4666 \n",
       "L 2450 4666 \n",
       "L 2450 531 \n",
       "L 3481 531 \n",
       "L 3481 0 \n",
       "L 794 0 \n",
       "L 794 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_2\">\n",
       "    <g id=\"ytick_1\">\n",
       "     <g id=\"line2d_7\">\n",
       "      <defs>\n",
       "       <path id=\"m525aa96a3c\" d=\"M 0 0 \n",
       "L -3.5 0 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#m525aa96a3c\" x=\"30.103125\" y=\"149.599219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_7\">\n",
       "      <!-- 0.0 -->\n",
       "      <g transform=\"translate(7.2 153.398438) scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_2\">\n",
       "     <g id=\"line2d_8\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m525aa96a3c\" x=\"30.103125\" y=\"121.879219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_8\">\n",
       "      <!-- 0.2 -->\n",
       "      <g transform=\"translate(7.2 125.678438) scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-32\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_3\">\n",
       "     <g id=\"line2d_9\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m525aa96a3c\" x=\"30.103125\" y=\"94.159219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_9\">\n",
       "      <!-- 0.4 -->\n",
       "      <g transform=\"translate(7.2 97.958438) scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-34\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_4\">\n",
       "     <g id=\"line2d_10\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m525aa96a3c\" x=\"30.103125\" y=\"66.439219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_10\">\n",
       "      <!-- 0.6 -->\n",
       "      <g transform=\"translate(7.2 70.238438) scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-36\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_5\">\n",
       "     <g id=\"line2d_11\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m525aa96a3c\" x=\"30.103125\" y=\"38.719219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_11\">\n",
       "      <!-- 0.8 -->\n",
       "      <g transform=\"translate(7.2 42.518438) scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-38\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_6\">\n",
       "     <g id=\"line2d_12\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m525aa96a3c\" x=\"30.103125\" y=\"10.999219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_12\">\n",
       "      <!-- 1.0 -->\n",
       "      <g transform=\"translate(7.2 14.798438) scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"95.410156\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"patch_3\">\n",
       "    <path d=\"M 30.103125 149.599219 \n",
       "L 30.103125 10.999219 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_4\">\n",
       "    <path d=\"M 225.403125 149.599219 \n",
       "L 225.403125 10.999219 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_5\">\n",
       "    <path d=\"M 30.103125 149.599219 \n",
       "L 225.403125 149.599219 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_6\">\n",
       "    <path d=\"M 30.103125 10.999219 \n",
       "L 225.403125 10.999219 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "  </g>\n",
       " </g>\n",
       "</svg>\n"
      ],
      "text/plain": [
       "<Figure size 350x250 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "embed_size, num_hiddens, num_layers, dropout = 32, 32, 2, 0.1\n",
    "batch_size, num_steps = 64, 10\n",
    "lr, num_epochs = 0.005, 300\n",
    "\n",
    "train_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)\n",
    "encoder = Seq2SeqEncoder(len(src_vocab), embed_size, num_hiddens, num_layers,\n",
    "                        dropout)\n",
    "decoder = Seq2SeqDecoder(len(tgt_vocab), embed_size, num_hiddens, num_layers,\n",
    "                        dropout)\n",
    "net = d2l.EncoderDecoder(encoder, decoder)\n",
    "\n",
    "train_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 48,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps, save_attention_weights=False):\n",
    "    \"\"\"序列到序列模型的预测\"\"\"\n",
    "    # 在预测时将net设置为评估模式\n",
    "    net.set_train(False)\n",
    "    src_tokens = src_vocab[src_sentence.lower().split(' ')] + [\n",
    "        src_vocab['<eos>']]\n",
    "    enc_valid_len = mindspore.Tensor([len(src_tokens)])\n",
    "    src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab['<pad>'])\n",
    "    # 添加批量轴\n",
    "    enc_X = ops.unsqueeze(mindspore.Tensor(src_tokens, mindspore.int32), 0)\n",
    "    enc_outputs = net.encoder(enc_X, enc_valid_len)\n",
    "    dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)\n",
    "    # 添加批量轴\n",
    "    dec_X = ops.unsqueeze(mindspore.Tensor([tgt_vocab['<bos>']], mindspore.int32), 0)\n",
    "    output_seq, attention_weight_seq = [], []\n",
    "    for _ in range(num_steps):\n",
    "        Y, dec_state = net.decoder(dec_X, dec_state)\n",
    "        # 我们使用具有预测最高可能性的词元，作为解码器在下一时间步的输入\n",
    "        dec_X = Y.argmax(axis=2)\n",
    "        pred = int(dec_X.squeeze(0).asnumpy())\n",
    "        # 保存注意力权重（稍后讨论）\n",
    "        if save_attention_weights:\n",
    "            attention_weight_seq.append(net.decoder.attention_weights)\n",
    "        # 一旦序列结束词元被预测，输出序列的生成就完成了\n",
    "        if pred == tgt_vocab['<eos>']:\n",
    "            break\n",
    "        output_seq.append(pred)\n",
    "    return ' '.join(tgt_vocab.to_tokens(output_seq)), attention_weight_seq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "BLEU的代码实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 51,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def bleu(pred_seq, label_seq, k):  \n",
    "    \"\"\"计算BLEU\"\"\"\n",
    "    pred_tokens, label_tokens = pred_seq.split(' '), label_seq.split(' ')\n",
    "    len_pred, len_label = len(pred_tokens), len(label_tokens)\n",
    "    score = math.exp(min(0, 1 - len_label / len_pred))\n",
    "    for n in range(1, k + 1):\n",
    "        num_matches, label_subs = 0, collections.defaultdict(int)\n",
    "        for i in range(len_label - n + 1):\n",
    "            label_subs[''.join(label_tokens[i: i + n])] += 1\n",
    "        for i in range(len_pred - n + 1):\n",
    "            if label_subs[''.join(pred_tokens[i: i + n])] > 0:\n",
    "                num_matches += 1\n",
    "                label_subs[''.join(pred_tokens[i: i + n])] -= 1\n",
    "        score *= math.pow(num_matches / (len_pred - n + 1), math.pow(0.5, n))\n",
    "    return score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "将几个英语句子翻译成法语"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 53,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "engs = ['go .', \"i lost .\", 'he\\'s calm .', 'i\\'m home .']\n",
    "fras = ['va !', 'j\\'ai perdu .', 'il est calme .', 'je suis chez moi .']\n",
    "for eng, fra in zip(engs, fras):\n",
    "    translation, attention_weight_seq = predict_seq2seq(\n",
    "        net, eng, src_vocab, tgt_vocab, num_steps)\n",
    "    print(f'{eng} => {translation}, bleu {bleu(translation, fra, k=2):.3f}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "ms_d2l",
   "language": "python",
   "name": "ms_d2l"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  },
  "rise": {
   "autolaunch": true,
   "enable_chalkboard": true,
   "overlay": "<div class='my-top-right'><img height=80px src='http://d2l.ai/_static/logo-with-text.png'/></div><div class='my-top-left'></div>",
   "scroll": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
